import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/widget/check/check_dialog_detail.dart';
import 'package:material_collection_app/widget/check/check_dialog_result.dart';
import '../utils/utils.dart';

class CheckResultPage extends StatefulWidget {
  final Map arguments;

  CheckResultPage({Key key, this.arguments}) : super(key: key);

  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<CheckResultPage> {
  List<String> rfidList = [];
  List materialList = [];
  int matchingNum = 0;
  int noMatchingNum = 0;
  String btnType = 'all';
  bool checkStatus = false;

  var eventBus = new EventBus();

  @override
  void initState() {
    super.initState();
    setState(() {
      rfidList = widget.arguments['list'];
    });
    getList();
  }

  // 获取物资列表
  void getList() async {
    DioUtils.request("InventoryTask/goods",
        context: context,
        method: "POST",
        params: {'id': widget.arguments['id']}, onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          materialList = res['data'];
          debugPrint('物资列表数据：${res['data']}');
        });
        _matchingRFID();
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {
      debugPrint('物资列表数据错误：$error');
    });
  }

  _matchingRFID() {
    for (var i = 0; i < materialList.length; i++) {
      var item = materialList[i];

      if (item['rfid_code'] == '' || item['rfid_code'] == null) {
        item['rfid_result'] = '';
        noMatchingNum++;
        continue;
      }

      if (rfidList.indexOf(item['rfid_code']) != -1) {
        item['rfid_result'] = '1';
        matchingNum++;
      } else {
        item['rfid_result'] = '0';
        noMatchingNum++;
      }
    }

    if (noMatchingNum == 0) {
      checkStatus = true;
    } else {
      checkStatus = false;
    }

    setState(() {
      materialList = materialList;
    });
  }

  _buildTableRow() {
    List<TableRow> list = [];

    list.add(
      TableRow(
          //第一行样式 添加背景色
          decoration: BoxDecoration(color: Utils.hexToColor('#F2F8FF')),
          children: [
            SizedBox(
                height: 40.0,
                child: Center(
                  child: Text('序号',
                      style: TextStyle(
                          color: Utils.hexToColor('#666666'),
                          fontWeight: FontWeight.bold)),
                )),
            Center(
              child: Text('入库单号',
                  style: TextStyle(
                      color: Utils.hexToColor('#666666'),
                      fontWeight: FontWeight.bold)),
            ),
            Center(
              child: Text('物资名称',
                  style: TextStyle(
                      color: Utils.hexToColor('#666666'),
                      fontWeight: FontWeight.bold)),
            ),
            Center(
              child: Text('物资编号',
                  style: TextStyle(
                      color: Utils.hexToColor('#666666'),
                      fontWeight: FontWeight.bold)),
            ),
            Center(
              child: Text('存放位置',
                  style: TextStyle(
                      color: Utils.hexToColor('#666666'),
                      fontWeight: FontWeight.bold)),
            ),
            Center(
              child: Text('匹配',
                  style: TextStyle(
                      color: Utils.hexToColor('#666666'),
                      fontWeight: FontWeight.bold)),
            )
          ]),
    );

    for (var i = 0; i < materialList.length; i++) {
      var item = materialList[i];

      if (btnType == 'all') {
        list.add(_buildRow(list, item, i));
      }

      if (btnType == 'yes' &&
          item['rfid_result'] != null &&
          item['rfid_result'] == '1') {
        list.add(_buildRow(list, item, i));
      }

      if (btnType == 'wrong' &&
          item['rfid_result'] != null &&
          item['rfid_result'] != '1') {
        list.add(_buildRow(list, item, i));
      }
    }

    return list;
  }

  _buildRow(list, item, i) {
    return TableRow(children: [
      //序号
      GestureDetector(
        onTap: () {
          this.showChecDetailDialog(item);
        },
        child: SizedBox(
            height: 40.0,
            child: Center(
              child: Text((i + 1).toString()),
            )),
      ),
      //入库单号
      GestureDetector(
        onTap: () {
          this.showChecDetailDialog(item);
        },
        child: Center(
          child: Text(item['enterOrders__order_no']),
        ),
      ),
      //物资名称
      GestureDetector(
        onTap: () {
          this.showChecDetailDialog(item);
        },
        child: Center(
          child: Text(item['goods_name']),
        ),
      ),
      //物资编号
      GestureDetector(
        onTap: () {
          this.showChecDetailDialog(item);
        },
        child: Center(
          child: Text(item['code']),
        ),
      ),
      //存放位置
      GestureDetector(
        onTap: () {
          this.showChecDetailDialog(item);
        },
        child: Center(
          child: Text(item['store__store_name'] +
              ' ' +
              item['storeLibrary__library_name'] +
              ' ' +
              (item['storeDetail__detail_code'] != null
                  ? item['storeDetail__detail_code']
                  : '')),
        ),
      ),
      //匹配
      GestureDetector(
          onTap: () {
            this.showChecDetailDialog(item);
          },
          child: Center(
            child: Image.asset(
                // item['rfid_result'] != null && item['rfid_result'] == 'yes'
                item['rfid_result'] != null && item['rfid_result'] == '1'
                    ? 'assets/yes.png'
                    : 'assets/wrong.png',
                width: 20),
          ))
    ]);
  }

  Widget _buildTopButtons() {
    return Align(
      child: Container(
        height: 50,
        color: Utils.hexToColor('#FFFFFF'),
        padding: EdgeInsets.symmetric(horizontal: 10),
        margin: EdgeInsets.only(bottom: 30.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Row(
              children: <Widget>[
                _buildTopButton(
                    '物资(' + materialList.length.toString() + ')',
                    'all',
                    'assets/add.png',
                    Alignment.centerLeft,
                    BorderRadius.horizontal(left: Radius.circular(30)),
                    btnType == 'all' ? '#FFFFFF' : '#666666',
                    btnType == 'all' ? '#297CFF' : '#F5F3F3'),
                _buildTopButton(
                    '匹配(' + matchingNum.toString() + ')',
                    'yes',
                    'assets/submit.png',
                    Alignment.centerRight,
                    BorderRadius.horizontal(right: Radius.circular(30)),
                    btnType == 'yes' ? '#FFFFFF' : '#666666',
                    btnType == 'yes' ? '#297CFF' : '#F5F3F3'),
                _buildTopButton(
                    '有误(' + noMatchingNum.toString() + ')',
                    'wrong',
                    'assets/submit.png',
                    Alignment.centerRight,
                    BorderRadius.horizontal(right: Radius.circular(30)),
                    btnType == 'wrong' ? '#FFFFFF' : '#666666',
                    btnType == 'wrong' ? '#297CFF' : '#F5F3F3'),
              ],
            ),
            _buildTopButton(
                '保存',
                'save',
                'assets/submit.png',
                Alignment.centerRight,
                BorderRadius.horizontal(right: Radius.circular(30)),
                '#FFFFFF',
                '#FF9232'),
            _buildTopButton(
                '提交',
                'submit',
                'assets/submit.png',
                Alignment.centerRight,
                BorderRadius.horizontal(right: Radius.circular(30)),
                '#FFFFFF',
                '#FF9232'),
          ],
        ),
      ),
    );
  }

  // 抽取公共方法：构建底部按钮
  Widget _buildTopButton(
      String title,
      String type,
      String image,
      Alignment align,
      BorderRadius borderRadius,
      String color,
      String bgColor) {
    return Align(
        alignment: align,
        child: GestureDetector(
            onTap: () {
              if (type == 'submit') {
                //点击提交
                // Utils.openAlert('确定要提交吗？', context).then((confirm) => {
                //   if(confirm) {
                //   }
                // });

                this.showCheckResultDialog();
              } else if (type == 'save') {
                //点击保存
                _saveResult();
              } else {
                setState(() {
                  btnType = type;
                });
              }
            },
            child: Container(
              child: Text(
                title,
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Utils.hexToColor(color)),
              ),
              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
              decoration: BoxDecoration(
                  color: Utils.hexToColor(bgColor),
                  borderRadius: BorderRadius.all(Radius.circular(4.0))),
              margin: EdgeInsets.only(right: type != 'submit' ? 8 : 0),
            )));
  }

  // 盘点结果
  Future<void> showCheckResultDialog({Map item}) async {
    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.w))),
              insetPadding: EdgeInsets.all(0),
              child: CheckDialogResult(
                materialLength: materialList.length,
                matchingNum: matchingNum,
                noMatchingNum: noMatchingNum,
                checkStatus: checkStatus,
                onSubmit: (remark) {
                  submit(remark);
                },
              ));
        });
  }

  // 物资详情
  Future<void> showChecDetailDialog(Map item) async {
    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.w))),
              insetPadding: EdgeInsets.all(0),
              child: CheckDialogDetail(item: item));
        });
  }

  //保存盘点结果
  void _saveResult() {
    DioUtils.request("InventoryTask/submit",
        context: context,
        method: "POST",
        params: {
          'id': widget.arguments['id'],
          'goods_num': materialList.length,
          'matching_goods_num': matchingNum,
          'error_goods_num': noMatchingNum,
          'status': 22, //保存时候专用status
          'material_rfid': rfidList,
          'inventory_remark': ''
        }, onSuccess: (res) {
      Utils.showText(text: res['msg']);

      if (res['code'] == 1) {
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        eventBus.emit('check_submit', {'index': widget.arguments['itemIndex']});
      }
    }, onError: (error) {});
  }

  //提交盘点结果
  void submit(remark) {
    DioUtils.request("InventoryTask/submit",
        context: context,
        method: "POST",
        params: {
          'id': widget.arguments['id'],
          'goods_num': materialList.length,
          'matching_goods_num': matchingNum,
          'error_goods_num': noMatchingNum,
          'status': 10,
          'material_rfid': rfidList,
          'inventory_remark': remark
        }, onSuccess: (res) {
      Utils.showText(text: res['msg']);

      if (res['code'] == 1) {
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        eventBus.emit('check_submit', {'index': widget.arguments['itemIndex']});
      }
    }, onError: (error) {});
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return WillPopScope(
        child: Scaffold(
            appBar: AppBar(
              centerTitle: true,
              title: Text(
                '盘点结果',
                style: TextStyle(color: Colors.white, fontSize: 17.0),
              ),
              leading: Padding(
                padding: EdgeInsets.fromLTRB(0.w, 25.w, 35.w, 24.w),
                child: SizedBox(
                  width: 24.w,
                  height: 24.w,
                  child: IconButton(
                    onPressed: () {
                      //判断页面来源
                      var page = widget.arguments['page'];
                      if (page == 'scan_results_page') {
                        // 回退两级页面
                        Navigator.pop(context);
                        Navigator.pop(context);
                      } else {
                        Navigator.pop(context);
                      }
                    },
                    icon: ImageIcon(AssetImage('assets/arrow_return.png'),
                        color: Colors.white),
                  ),
                ),
              ),
              backgroundColor: Color(0xFF297CFF),
            ),
            body: Container(
                color: Utils.hexToColor('#F5F6FA'),
                child: Stack(children: <Widget>[
                  RawKeyboardListener(
                      focusNode: FocusNode(), // 焦点
                      autofocus: true,
                      onKey: (RawKeyEvent event) {
                        if (event.runtimeType.toString() == 'RawKeyDownEvent') {
                          RawKeyEventDataAndroid data =
                              event.data as RawKeyEventDataAndroid;
                          String _keyCode;
                          _keyCode = data.keyCode
                              .toString(); //keycode of key event (66 is return)

                          if (_keyCode == '280' ||
                              _keyCode == '293' ||
                              _keyCode == '139') {
                            // readTagFromBuffer();
                          }
                        }
                      },
                      child: Column(
                        children: <Widget>[
                          _buildTopButtons(),
                          ConstrainedBox(
                            constraints: BoxConstraints(
                              maxHeight: 0,
                            ),
                            child: new TextField(
                              showCursor: false,
                              autofocus: true,
                              decoration: InputDecoration(
                                border: OutlineInputBorder(
                                    borderSide: BorderSide.none),
                              ),
                            ),
                          ),
                          Expanded(
                              child: Offstage(
                                  offstage: false,
                                  child: Column(children: <Widget>[
                                    Expanded(
                                        child: SingleChildScrollView(
                                            child: Column(
                                      children: <Widget>[
                                        Table(
                                            columnWidths: const {
                                              //列宽
                                              0: FixedColumnWidth(50.0),
                                            },
                                            //表格边框样式
                                            border: TableBorder.all(
                                              color:
                                                  Utils.hexToColor('#DCDFE6'),
                                              width: 1,
                                              style: BorderStyle.solid,
                                            ),
                                            defaultVerticalAlignment:
                                                TableCellVerticalAlignment
                                                    .middle,
                                            children: _buildTableRow()),
                                      ],
                                    )))
                                  ])))
                        ],
                      ))
                ]))),
        onWillPop: () {
          debugPrint('点击了返回');
          //实现WillPopScope小部件来处理Android返回键的行为。WillPopScope小部件允许你拦截返回事件并决定自己的行为
          //判断页面来源
          var page = widget.arguments['page'];
          if (page == 'scan_results_page') {
            // 回退两级页面
            Navigator.pop(context);
            Navigator.pop(context);
          } else {
            Navigator.pop(context);
          }
        });
  }
}
